<template>
	<view>
		<uni-file-picker v-model="videoData" fileMediatype="video" mode="grid" @select="select" @delete="deleteFile" />
		<view class="file-item">
			<sunny-video :videoHeight="120" v-for="(item,index) in videoData" :key="index" :src="item.url" :title="item.name"
				:video-id="'videoId'+index" />
		</view>
	</view>
</template>

<script>
	import constant from "@/utils/constant.js"

	export default {
		data() {
			return {
				fileHost: constant.fileHost,
				videoData: [],
				appendFiles: [],
				originFiles: [],
				uuid: "",
			}
		},
		onLoad(option) {
			this.uuid = option.uuid;
			if (option.videoUrls) {
				const videoUrls = JSON.parse(decodeURIComponent(option.videoUrls));
				const serverData = videoUrls.map(item => {
					let url = item;
					if (url.indexOf("/storage") < 0) {
						url = this.fileHost + url;
					}
					const name = item.split("/");
					const fileName = name[name.length - 1];
					this.originFiles.push({
						url: item,
						name: fileName
					})
					return {
						url: url,
						name: fileName,
						extname: fileName.split(".")[1]
					};
				});
				this.videoData = [
					...serverData,
					...this.getStoreFile
				];
			} else {
				this.videoData = this.getStoreFile;
				this.appendFiles = this.getStoreFile;
			}
		},
		computed: {
			getStoreFile() {
				return this.$store.state.file[`video_files_${this.uuid}`]?.appendFiles || []
			}
		},
		methods: {
			// 获取上传状态
			select(e) {
				e.tempFiles.forEach(item => {
					this.videoData.push({
						name: item.name,
						extname: item.extname,
						url: item.url,
					});
					this.appendFiles.push({
						name: item.name,
						extname: item.extname,
						url: item.url,
					})
				});
				this.$store.commit('SAVE_VIDEO', {
					uuid: this.uuid,
					files: {
						originFiles: this.originFiles,
						appendFiles: this.appendFiles
					}
				})
			},
			deleteFile(e) {
				const delFile = e.tempFile.name
				this.videoData = this.videoData.filter(item => {
					return item.name !== delFile
				})
				this.originFiles = this.originFiles.filter(item => {
					return item.name !== delFile
				})
				this.appendFiles = this.appendFiles.filter(item => {
					return item.name !== delFile
				})
				this.$store.commit('SAVE_VIDEO', {
					uuid: this.uuid,
					files: {
						originFiles: this.originFiles,
						appendFiles: this.appendFiles
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.file-item {
		padding: 0 10px;
		margin-top: 10px;

		.video-item {
			height: 120px;
			width: 120px;
		}
	}
</style>